﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChapterX.Common;
using ChapterX.BusinessFacade;
using ChapterX.Data;
using ChapterX.Data.ChaptersDSTableAdapters;
using System.Data;

namespace ChapterX.Modules
{
    public partial class BookChapterEntry : ChapterX.Model.ModuleBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Utils.HasValue(Request.QueryString[QueryKeys.BOOK_ID]))
                {
                    this.hf_BookId.Value = Utils.GetValue(Request.QueryString[QueryKeys.BOOK_ID]);
                    if (Utils.HasValue(Request.QueryString[QueryKeys.CHAPTER_ID]))
                    {
                        this.hf_ChapterId.Value = Utils.GetValue(Request.QueryString[QueryKeys.CHAPTER_ID]);
                        this.row_UploadedFile.Visible = true;
                    }
                    else
                    {
                        this.hf_ChapterId.Value = String.Empty;
                        this.row_UploadedFile.Visible = false;
                    }

                    BindChapter();
                }
                else
                {
                    this.hf_BookId.Value = String.Empty;
                    this.row_UploadedFile.Visible = false;
                }
            }
        }

        protected void BindChapter()
        {
            int chapterId;

            if (Utils.HasValue(this.hf_ChapterId.Value) && Int32.TryParse(this.hf_ChapterId.Value, out chapterId))
            {
                try
                {
                    ChapterSystem cs = new ChapterSystem();
                    ChaptersDS.ChaptersRow chapter = cs.GetChapterByChapterId(chapterId);
                    if(chapter == null)
                    {
                        throw new RecordNotExistedException();
                        
                    }

                    this.tb_Seq.Text = Utils.FilterHtml(chapter.Seq.ToString());
                    this.tb_Title.Text = Utils.FilterHtml(chapter.Title);
                    if (!chapter.IsDescsNull())
                    {
                        this.tb_Desc.Text = Utils.FilterHtml(chapter.Descs);
                    }
                    this.hl_FilePath.Text = Utils.FilterHtml(chapter.FilePath);

                }
                catch (Exception ex)
                {
                    SetErrorMessage(ex.Message);
                    Logger.Log(ex);
                }
            }
        }

        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                ChapterSystem cs = new ChapterSystem();
                ChaptersDS.ChaptersRow chapter = cs.ChapterSchema.NewChaptersRow();

                if (Utils.HasValue(this.hf_ChapterId.Value))
                {
                    try
                    {
                        chapter.ChapterId = Int32.Parse(this.hf_ChapterId.Value);
                    }
                    catch
                    {
                        throw new UnexpectedException();
                    }
                }
                else
                {
                    chapter.ChapterId = -1;
                }

                try
                {
                    chapter.Seq = Int32.Parse(this.tb_Seq.Text.Trim());
                }
                catch
                {
                    throw new InvalidExpressionException("序号字段值无效，请输入正整数");
                }

                if (this.tb_Title.Text.Trim().Length == 0)
                {
                    throw new InvalidInputException("请输入文件标题");
                }

                if (this.tb_Desc.Text.Trim().Length == 0)
                {
                    throw new InvalidInputException("请输入文件简介");
                }

                if (!this.fu_FileUpload.HasFile)
                {
                    throw new InvalidInputException("请选择要上传的文件");
                }
                

                if (Utils.HasValue(this.hf_BookId.Value))
                {
                    try
                    {
                        chapter.BookId = Int32.Parse(this.hf_BookId.Value);
                        chapter.Descs = this.tb_Desc.Text;
                        chapter.Title = this.tb_Title.Text;


                        //ISBN_Seq  没有isbn
                        //获取ISBN，暂时用id代替
                        int index = this.fu_FileUpload.FileName.LastIndexOf(".");
                        String suffix = this.fu_FileUpload.FileName;
                        suffix = suffix.Substring(index + 1, suffix.Length - index - 1);
                        String fileName = String.Format("{0}_{1}.{2}", chapter.BookId.ToString(), chapter.Seq.ToString(), suffix);
                        chapter.FilePath = fileName;

                        
                        this.fu_FileUpload.SaveAs(String.Format("{0}{1}", UploadSystem.GetIngestPath(HttpContext.Current), fileName));


                        bool result = cs.SubmitChapter_Default(chapter);
                        if (result)
                            SetInfoMessage("章节提交成功");
                        else
                            SetErrorMessage("章节提交失败");
                    }
                    catch(Exception ex)
                    {
                        SetErrorMessage("章节提交失败");
                        Logger.Log(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                SetErrorMessage(String.Format("章节提交失败:{0}",ex.Message));
                Logger.Log(ex);
            }
        }

        protected void btn_Return_Click(object sender, EventArgs e)
        {
            Response.Redirect(String.Format("ChapterList.aspx?{0}={1}", QueryKeys.BOOK_ID, this.hf_BookId.Value));
        }
    }
}